package cn.krui.project.controller.system;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;

import cn.krui.helper.bean.AppResult;
import cn.krui.helper.tools.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import sun.misc.BASE64Encoder;

/**
 * @program: project-system
 * @description: 图片验证码
 * @author: zc
 * @create: 2019-10-16
 **/
@SuppressWarnings("restriction")
@RestController
@RequestMapping(value = "/system/kaptcha")
@Api(tags = "通用-图形验证码", description = "图形验证码")
@CrossOrigin
public class CaptchImageAction extends SystemBaseController {
	@Autowired
	private Producer captchaProducer;

	@Autowired
	private RedisUtils rUtils;

	@PostMapping(value = "/captchaImage")
	@ApiOperation(value = "图形验证码", httpMethod = "POST")
	public AppResult<?> getKaptchaImage(@ApiParam(value = "获取数据对应的uuid", required = false) String uuid) throws Exception {
		AppResult<Map<String, Object>> app = new AppResult<Map<String, Object>>();
		String capText = captchaProducer.createText();
		BufferedImage bi = captchaProducer.createImage(capText);
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ImageIO.write(bi, "jpg", outputStream);
		BASE64Encoder encoder = new BASE64Encoder();
		String base64Img = encoder.encode(outputStream.toByteArray());
		Map<String, Object> map = new HashMap<>(2);
		map.put("capText", uuid);
		map.put("base64Img", base64Img);
		rUtils.set("other_token:" + uuid, capText);
		app.setDataSingle(map);
		app.ok("成功");
		return app;
	}

}
